<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="订单号">
        <el-input
          v-model="searchObj.orderNo"
          placeholder="订单号"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="课程名称">
        <el-input
          v-model="searchObj.courseTitle"
          placeholder="课程名称"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="用户昵称">
        <el-input
          v-model="searchObj.nickname"
          placeholder="用户昵称"
          style="width: 190px"
        />
      </el-form-item>

      <el-form-item label="订单状态">
        <el-select
          v-model="searchObj.status"
          clearable
          placeholder="订单状态"
          style="width: 110px"
        >
          <el-option label="未支付" value="0" />
          <el-option label="已支付" value="1" />
          <el-option label="已取消" value="2" />
        </el-select>
      </el-form-item>

      <el-button
        type="primary"
        icon="el-icon-search"
        @click="fetchData()"
        style="width: 80px"
        >查询</el-button
      >
      <el-button type="default" @click="resetData()" style="width: 60px"
        >清空</el-button
      >
    </el-form>

    <!-- 订单列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="orderNo" label="订单号" width="180" />

      <el-table-column prop="courseTitle" label="课程名称" width="200">
        <template slot-scope="scope">
          <el-tooltip placement="top">
            <div slot="content">
              <img :src="scope.row.courseCover" width="200" />
            </div>
            <span>{{ scope.row.courseTitle }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="nickname" label="用户昵称" width="180" />

      <el-table-column prop="totalFee" label="支付金额" width="80">
        <template slot-scope="scope">
          {{ scope.row.totalFee }}元
        </template>
      </el-table-column>

      <el-table-column prop="status" label="订单状态" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="
              scope.row.status === 1
                ? 'success'
                : scope.row.status === 2
                ? 'danger'
                : 'warning'
            "
          >
            {{
              scope.row.status === 1
                ? "已支付"
                : scope.row.status === 2
                ? "已取消"
                : "未支付"
            }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="gmtCreate" label="创建时间" width="160" />

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button 
            type="primary"
            size="mini"
            @click="showDetail(row.orderNo)">
            查看
          </el-button>
          <el-button 
            size="mini"
            type="danger"
            @click="handleDelete(row.orderNo)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[10]"
      style="padding: 30px 0; text-align: center"
      layout="total, prev, pager, next, jumper"
      @current-change="changeCurrentPage"
    />

    <!-- 订单详情 -->
    <el-dialog title="详情" :visible.sync="dialogVisible" width="60%">
      <h3>订单信息</h3>
      <div class="dialog-content">
        <div class="detail-item">
          <span class="label">订单号：</span>
          <span class="value">{{orderInfo.orderNo}}</span>
        </div>
        <div class="detail-item">
          <span class="label">课程名称：</span>
          <span class="value">{{orderInfo.courseTitle}}</span>
        </div>
        <div class="detail-item">
          <span class="label">用户昵称：</span>
          <span class="value">{{orderInfo.nickname}}</span>
        </div>
        <div class="detail-item">
          <span class="label">支付金额：</span>
          <span class="value">{{ orderInfo.totalFee}}元</span>
        </div>
        <div class="detail-item">
          <span class="label">订单状态：</span>
          <span class="value">{{
            orderInfo.status === 1
              ? "已支付"
              : orderInfo.status === 2
              ? "已取消"
              : orderInfo.status === 0
              ? "未支付"
              : "未知"
          }}</span>
        </div>
        <div class="detail-item">
          <span class="label">创建时间：</span>
          <span class="value">{{ orderInfo.gmtCreate }}</span>
        </div>
      </div>

      <el-divider></el-divider>

      <h3>支付信息</h3>
      <div class="dialog-content" :column="2" border v-if="payLog">
        <div class="detail-item">
          <span class="label">支付方式：</span>
          <span class="value">{{
            payLog.payType === 1
              ? "微信支付"
              : payLog.payType === 2
              ? "支付宝"
              : "未知"
          }}</span>
        </div>
        <div class="detail-item">
          <span class="label">支付时间：</span>
          <span class="value">{{ payLog.payTime }}</span>
        </div>
        <div class="detail-item">
          <span class="label">交易流水号：</span>
          <span class="value">{{ payLog.transactionId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">支付状态：</span>
          <span class="value">{{
            payLog.tradeState === "SUCCESS" ? "支付成功" : "支付失败"
          }}</span>
        </div>
      </div>
      <el-empty description="暂无支付信息" v-else></el-empty>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import orderApi from "@/api/admin/order"

export default {
  data() {
    return {
      listLoading: true, // 数据是否正在加载
      list: null, // 订单列表
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      searchObj: {}, // 查询表单对象
      dialogVisible: false, // 详情对话框是否可见
      orderInfo: {
        orderNo: "",
        courseTitle: "",
        nickname: "",
        totalFee: 0,
        status: 0,
        gmtCreate: "",
      }, // 订单详情
      payLog: null, // 支付记录
    };
  },

  created() {
    this.fetchData()
  },

  methods: {
    // 加载订单列表数据
    fetchData() {
      this.listLoading = true

      const filteredParams = { ...this.searchObj }
      Object.keys(filteredParams).forEach((key) => {
        if (filteredParams[key] === "" || filteredParams[key] === undefined) {
          delete filteredParams[key]
        }
        if (key === "status" && filteredParams[key] !== null) {
          filteredParams[key] = parseInt(filteredParams[key])
        }
      });
      console.log("请求参数:", filteredParams)

      orderApi
        .getOrderList(this.page, this.limit, filteredParams)
        .then((response) => {
          console.log("返回数据:", response.data)
          this.list = response.data.items
          this.total = response.data.total
          this.listLoading = false
        })
        .catch((error) => {
          console.error("加载订单列表失败:", error)
          this.listLoading = false
          this.$message.error("加载订单列表失败")
        });
    },
    changeCurrentPage(page) {
      this.page = page
      this.fetchData()
    },

    // 重置查询表单
    resetData() {
      this.searchObj = {
        orderNo: "",
        courseTitle: "",
        nickname: "",
        status: null
      }
      this.fetchData()
    },

    // 显示订单详情
    showDetail(orderNo) {
      this.dialogVisible = true
      this.orderInfo = { ...this.$options.data().orderInfo }
      this.payLog = null
      // 获取订单信息
      orderApi
        .getOrderInfo(orderNo)
        .then((response) => {
          if (response.data && response.data.order) {
            this.orderInfo = response.data.order
          } else {
            this.$message.error("订单数据格式错误")
          }
        })
        .catch((error) => {
          this.$message.error("获取订单详情失败")
          console.error(error)
        })
      // 获取支付记录
      orderApi.getPayLog(orderNo).then((response) => {
        if (response.data && response.data.payLog) {
          this.payLog = response.data.payLog
        }
      })
    },

    // 删除订单
    handleDelete(orderNo) {
      this.$confirm("确定要删除此订单吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return orderApi.deleteOrder(orderNo);
        })
        .then((response) => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.fetchData()
        })
        .catch((err) => {
          if (err === "cancel") {
            this.$message({
              type: "info",
              message: "已取消删除"
            })
          }
        })
    }
  }
}
</script>

<style scoped>
.el-descriptions {
  margin-bottom: 20px;
}
</style>